{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Correlating microstripline model to measurement\n",
    "\n",
    "## Target\n",
    "\n",
    "The aim of this example is to correlate the microstripline model to the measurement over 4 frequency decades from 1MHz to 5GHz.\n",
    "\n",
    "## Plan\n",
    "\n",
    "1. Two different lengths of microstripline are measured;\n",
    "2. Multiline method is used to compute the frequency dependent relative permittivity and loss angle of the dielectric;\n",
    "3. Microstripline model is fitted to the computed parameters by optimization;\n",
    "4. Checking the results by embedding the connectors and comparison against measurement;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from numpy import absolute, log10, real, sum\n",
    "from scipy.optimize import minimize\n",
    "\n",
    "import skrf as rf\n",
    "\n",
    "rf.stylely()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Measurement of two microstripline with different lengths\n",
    "The measurement where performed the 21th March 2017 on a Anritsu MS46524B 20GHz Vector Network Analyser. The setup is a linear frequency sweep from 1MHz to 10GHz with 10'000 points. Output power is 0dBm, IF bandwidth is 1kHz and neither averaging nor smoothing are used.\n",
    "\n",
    "The frequency range of interest is limited from 1MHz to 5GHz, but the measurement are up to 10GHz.\n",
    "\n",
    "MSLxxx is a L long, W wide, T thick copper microstripline on a H height substrate with bottom ground plane.\n",
    "\n",
    "| Name | L (mm) | W (mm) | H (mm) | T (um) | Substrate |\n",
    "| :--- | ---: | ---: | ---: | ---: | :--- |\n",
    "| MSL100 | 100 | 3.00 | 1.55 | 50 | FR-4 |\n",
    "| MSL200 | 200 | 3.00 | 1.55 | 50 | FR-4 |\n",
    "\n",
    "The milling of the artwork is performed mechanically with a lateral wall of 45°. A small top ground plane chunk connected by a vias array to bottom ground is provided to solder the connector top ground legs and provide some coplanar-like transition from coax to microstrip.\n",
    "\n",
    "The relative permittivity of the dielectric was assumed to be approximately 4.5 for design purpose.\n",
    "\n",
    "![MSL100 and MSL200 illustration, both are microstripline, MSL200 is twice the length of MSL100](MSL_CPWG_100_200.jpg \"MSL100 and MSL200\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load raw measurements\n",
    "MSL100_raw = rf.Network('MSL100.s2p')\n",
    "MSL200_raw = rf.Network('MSL200.s2p')\n",
    "\n",
    "# Keep only the data from 1MHz to 5GHz\n",
    "MSL100 = MSL100_raw['1-5000mhz']\n",
    "MSL200 = MSL200_raw['1-5000mhz']\n",
    "\n",
    "plt.figure()\n",
    "plt.title('Measured data')\n",
    "MSL100.plot_s_db()\n",
    "MSL200.plot_s_db()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The measured data shows that the electrical length of MSL200 is approximately twice the one of MSL100. The frequency spacing between Return Loss dips is approximately the half for MSL200 compared to MSL100. This is coherent with the physical dimensions if the small connector length is neglected.\n",
    "\n",
    "The MSL200 Insertion Loss is also about twice than MSL100, which is coherent as a longer path bring more attenuation.\n",
    "\n",
    "Return Loss under -20dB is usually considered to be fair for microstripline, it correspond to 1% of the power being reflected. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dielectric effective relative permittivity extraction by multiline method\n",
    "The phase of the measurements transmission parameter are subtracted. Because connectors are present on both DUTs, their length effect is canceled and the remaining phase difference is related to the difference of the DUTs length.\n",
    "\n",
    "Knowing the physical length $\\Delta L$ and the phase $\\Delta \\phi$, the effective relative permittivity constant $\\epsilon_{r,eff}$ can be computed from the relation\n",
    "$$\\left\\{ \\begin{array}{ll}\n",
    "\\lambda = \\frac{c_0}{f \\cdot \\sqrt{\\epsilon_{r,eff}}} \\\\\n",
    "\\phi = \\frac{2\\pi L}{\\lambda}\n",
    "\\end{array} \\right. \\implies\n",
    "\\epsilon_{r,eff} = \\left( \\frac{\\Delta \\phi \\cdot c_0}{2 \\pi f \\cdot \\Delta L} \\right)^2 $$\n",
    "\n",
    "In the same idea, the difference of Insertion Loss of the two DUT gives the Insertion Loss of the difference of the length and cancel connectors effects."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "c0       = 3e8\n",
    "f        = MSL100.f\n",
    "deltaL   = 0.1\n",
    "deltaPhi = np.unwrap(np.angle(MSL100.s[:,1,0])) - np.unwrap(np.angle(MSL200.s[:,1,0]))\n",
    "Er_eff   = np.power(deltaPhi * c0 / (2 * np.pi * f * deltaL), 2)\n",
    "Loss_mea = 20 * log10(absolute(MSL200.s[:,1,0] / MSL100.s[:,1,0]))\n",
    "\n",
    "plt.figure()\n",
    "plt.suptitle('Effective relative permittivity and loss')\n",
    "plt.subplot(2,1,1)\n",
    "plt.plot(f * 1e-9, Er_eff)\n",
    "plt.ylabel(r'$\\epsilon_{r,eff}$')\n",
    "\n",
    "plt.subplot(2,1,2)\n",
    "plt.plot(f * 1e-9, Loss_mea)\n",
    "plt.xlabel('Frequency (GHz)')\n",
    "plt.ylabel('Insertion Loss (dB)')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The effective relative permittivity of the geometry shows a dispersion effect at low frequency which can be modelled by a wideband Debye model such as *Djordjevic/Svensson* implementation of skrf microstripline media. The value then increase slowly with frequency which correspond roughly to the *Kirschning and Jansen* dispersion model.\n",
    "\n",
    "The Insertion Loss seems proportional to frequency, which indicate a predominance of the dielectric losses. Conductor losses are related to the square-root of frequency. Radiation losses are neglected."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fit microstripline model to the computed parameters by optimization\n",
    "\n",
    "### Effective relative permittivity\n",
    "Microstrip media model with the physical dimensions of the measured microstriplines is fitted to the computed $\\epsilon_{r,eff}$ by optimization of $\\epsilon_r$ and tand of the substrate at 1GHz. The dispersion model used to account for frequency variation of the parameters are *Djordjevic/Svensson* and *Kirschning and Jansen*."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from skrf.media import MLine\n",
    "\n",
    "W   = 3.00e-3\n",
    "H   = 1.55e-3\n",
    "T   = 50e-6\n",
    "L   = 0.1\n",
    "Er0   = 4.5\n",
    "tand0 = 0.02\n",
    "f_epr_tand = 1e9\n",
    "x0 = [Er0, tand0]\n",
    "\n",
    "def model(x, freq, Er_eff, L, W, H, T, f_epr_tand, Loss_mea):\n",
    "    ep_r = x[0]\n",
    "    tand = x[1]\n",
    "    m = MLine(frequency=freq, z0_port=50, w=W, h=H, t=T,\n",
    "        ep_r=ep_r, mu_r=1, rho=1.712e-8, tand=tand, rough=0.15e-6,\n",
    "        f_low=1e3, f_high=1e12, f_epr_tand=f_epr_tand,\n",
    "        diel='djordjevicsvensson', disp='kirschningjansen')\n",
    "    DUT  = m.line(L, 'm')\n",
    "    Loss_mod = 20 * log10(absolute(DUT.s[:,1,0]))\n",
    "    return sum((real(m.ep_reff_f) - Er_eff)**2) + 0.01*sum((Loss_mod - Loss_mea)**2)\n",
    "\n",
    "res = minimize(model, x0, args=(MSL100.frequency, Er_eff, L, W, H, T, f_epr_tand, Loss_mea),\n",
    "               bounds=[(4.2, 4.7), (0.001, 0.1)])\n",
    "Er   = res.x[0]\n",
    "tand = res.x[1]\n",
    "\n",
    "print(f'Er={Er:.3f}, tand={tand:.4f} at {f_epr_tand * 1e-9:.1f} GHz.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As a sanity check, the model data are compared with the computed parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = MLine(frequency=MSL100.frequency, z0_port=50, w=W, h=H, t=T,\n",
    "        ep_r=Er, mu_r=1, rho=1.712e-8, tand=tand, rough=0.15e-6,\n",
    "        f_low=1e3, f_high=1e12, f_epr_tand=f_epr_tand,\n",
    "        diel='djordjevicsvensson', disp='kirschningjansen')\n",
    "DUT  = m.line(L, 'm')\n",
    "DUT.name = 'DUT'\n",
    "Loss_mod = 20 * log10(absolute(DUT.s[:,1,0]))\n",
    "\n",
    "plt.figure()\n",
    "plt.suptitle('Measurement vs Model')\n",
    "plt.subplot(2,1,1)\n",
    "plt.plot(f * 1e-9, Er_eff, label='Measured')\n",
    "plt.plot(f * 1e-9, real(m.ep_reff_f), label='Model')\n",
    "plt.ylabel(r'$\\epsilon_{r,eff}$')\n",
    "plt.legend()\n",
    "\n",
    "plt.subplot(2,1,2)\n",
    "plt.plot(f * 1e-9, Loss_mea, label='Measured')\n",
    "plt.plot(f * 1e-9, Loss_mod, label='Model')\n",
    "plt.xlabel('Frequency (GHz)')\n",
    "plt.ylabel('Insertion Loss (dB)')\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The model results shows a reasonable agreement with the measured $\\epsilon_{r,eff}$ and Insertion Loss values."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Checking the results\n",
    "\n",
    "If the model is now plotted against the measurement of the same length, the plot shows no agreement. This is because the connector effects are not captured by the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure()\n",
    "plt.title('Measured vs modelled data')\n",
    "MSL100.plot_s_db()\n",
    "DUT.plot_s_db(0, 0, color='k')\n",
    "DUT.plot_s_db(1, 0, color='k')\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Connector delay and loss estimation\n",
    "\n",
    "The delay of the connector is estimated by fitting a line to its phase contribution vs frequency.\n",
    "\n",
    "The phase and loss of the two connector are computed by subtracting phase and loss computed without the connectors to the measurement of the same length."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "phi_conn = np.unwrap(np.angle(MSL100.s[:,1,0])) + deltaPhi\n",
    "z = np.polyfit(f, phi_conn, 1)\n",
    "p = np.poly1d(z)\n",
    "delay = -z[0]/(2*np.pi)/2\n",
    "print(f'Connector delay: {delay * 1e12:.0f} ps')\n",
    "\n",
    "loss_conn_db = 20 * log10(absolute(MSL100.s[:,1,0])) - Loss_mea\n",
    "alpha = 1.6*np.log(10)/20 * np.sqrt(f/1e9)\n",
    "beta  = 2*np.pi*f/c0\n",
    "gamma = alpha + 1j*beta\n",
    "mf = rf.media.DefinedGammaZ0(m.frequency, z0_port=50, z0=53.5, gamma=gamma)\n",
    "left = mf.line(delay*1e9, 'ns')\n",
    "right = left.flipped()\n",
    "check = left ** right\n",
    "\n",
    "plt.figure()\n",
    "plt.suptitle('Connector effects')\n",
    "plt.subplot(2,1,1)\n",
    "plt.plot(f * 1e-9, phi_conn, label='measured')\n",
    "plt.plot(f * 1e-9, np.unwrap(np.angle(check.s[:,1,0])), label='model')\n",
    "plt.ylabel('phase (rad)')\n",
    "plt.legend()\n",
    "\n",
    "plt.subplot(2,1,2)\n",
    "plt.plot(f * 1e-9, loss_conn_db, label='Measured')\n",
    "plt.plot(f * 1e-9, 20*np.log10(np.absolute(check.s[:,1,0])), label='model')\n",
    "plt.xlabel('Frequency (GHz)')\n",
    "plt.ylabel('Insertion Loss (dB)')\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The phase of the model shows a good agreement, while the Insertion Loss seems to have a reasonable agreement and is small whatsoever."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Connector impedance adjustment by time-domain reflectometry\n",
    "\n",
    "Time-domain step responses of  measurement and model are used to adjust the connector model characteristic impedance.\n",
    "\n",
    "The plots shows the connector having an inductive behaviour (positive peak) and the microstripline being a bit too much capacitive (negative plateau).\n",
    "\n",
    "Characteristic impedance of the connector is tuned by trial-and-error until a reasonable agreement is achieved. Optimization could have been used instead.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mod = left ** DUT ** right\n",
    "mod.name = 'Model'\n",
    "\n",
    "MSL100_dc = MSL100.extrapolate_to_dc(kind='cubic')\n",
    "DUT_dc = mod.extrapolate_to_dc(kind='cubic')\n",
    "\n",
    "plt.figure()\n",
    "plt.suptitle('Left-right and right-left TDR')\n",
    "plt.subplot(2,1,1)\n",
    "MSL100_dc.plot_z_time_step(0, 0)\n",
    "DUT_dc.plot_z_time_step(0, 0)\n",
    "plt.xlim(-2, 4)\n",
    "\n",
    "plt.subplot(2,1,2)\n",
    "MSL100_dc.plot_z_time_step(1, 1)\n",
    "DUT_dc.plot_z_time_step(1, 1)\n",
    "plt.xlim(-2, 4)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Final comparison"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure()\n",
    "plt.title('Measured vs modelled data')\n",
    "MSL100.plot_s_db()\n",
    "mod.name = 'Model'\n",
    "mod.plot_s_db(0, 0, color='k')\n",
    "mod.plot_s_db(1, 0, color='k')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The plot shows a decent agreement between the model and the measured data. The model is a good representation of the DUT between 1MHz and 5 GHz.\n",
    "\n",
    "At higher frequency, the model begin to deviate from the measurement. The model does not capture effects such as radiation loss or complex copper roughness. Smaller geometries such as the top ground plane chunk may also begin to contribute as they become electrically long with the increase of frequency.\n",
    "\n",
    "As a comparison, the 5GHz wavelength is 60mm in the air and the MSL100 line is 100mm long. The DUT itself is electrically long above some GHz.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
